import store from '../../store';
import aesJs from '@/common/utils/aes-js';

/**
 * 获取用户最新的加密秘钥数据
 * 
*/
export function getLatestUserManager() {
  return new Promise((resolve) => {
    const userCryptoManager = wx.getUserCryptoManager();
    userCryptoManager.getLatestUserKey({
      success: managerRes => {
        store.commit('setLatestUserKey', managerRes);
        resolve(managerRes)
      },
      fail: err => {
        reject(err)
      }
    })
  })
}

/**
 * 微信验证session是否过期，如果回调成功表示未过期
 * 相反则代表已过期，需要重新调用wx.login登录接口
*/
export function checkSessionThenLogin() {
  return new Promise((resolve, reject) => {
    wx.checkSession({
      success() {
        resolve('succ');
      },
      fail() {
        // session_key 已经失效，需要重新执行登录流程
        uni.login({
          success: (data) => {
            let url = `${store.state.domain}/account/mall/api/login`
            if (store.state.debug) {
              url = `${store.state.debugDomain}/account/mall/api/login`
            }
            let reqData = { code: data.code, puid: store.state.puid, type: store.state.platform }
            uni.request({
              url: url,
              method: 'POST',
              data: reqData,
              success: (response) => {
                let { token, expire, jwttoken } = response.data.detail;
                uni.setStorage({
                  key: 'token',
                  data: { token: token, jwttoken: jwttoken, expire: expire * 1000, created: (new Date()).getTime() },
                  success: () => {
                    resolve(response.data)
                  },
                  fail: () => {
                    reject('error')
                  }
                })
              },
              fail: (err) => {
                reject(err)
              }
            })
          },
          fail: (err) => {
            reject(err)
          }
        })
      }
    })
  })
}


/**
 * 使用aesjs内的cbc解密方式,通过传递key和iv参数获得实例对象
 * 将获得的加密数据转为字节,再进行decrypt解密,再将字节转为字符串
 * 把字符串解析为对象即可
 * @param {String} encryptData 加密的数据
*/
export function aesCbcDecrypt(encryptData) {
  return new Promise((resolve) => {
    //将获取的秘钥key、iv转为字节数据
    const key_ = aesJs.utils.utf8.toBytes(store.state.latestUserKey.encryptKey);
    const iv_ = aesJs.utils.utf8.toBytes(store.state.latestUserKey.iv);

    let newAes = new aesJs.ModeOfOperation.cbc(key_, iv_);

    let encryptedBytes = aesJs.utils.hex.toBytes(encryptData);

    let decryptedBytes = newAes.decrypt(encryptedBytes);

    let decryptedText = aesJs.utils.utf8.fromBytes(decryptedBytes);

    let decryJson = JSON.parse(decryptedText);

    newAes = null;

    resolve(decryJson);
  })
}